const now = new Date();

window.store.registerModule('chat', {
    namespaced: true,
    state: {
        ws: null,
        user: {},
        sessions: [],
        // 当前选中的会话
        currentSessionId: '',
        // 过滤出只包含这个key的会话
        filterKey: ''
    },
    mutations: {
        SET_USERS({ user }, content) {
            user = Object.assign({}, content)
        },
        INIT_WS(state, content) {
            const use = window.store.state.userInfo
            const data = Object.assign(use, content);
            window.store.commit('chat/SET_USERS', data)
            state.ws = new WebSocket(`ws://172.18.19.4:8099/xxpt/web/PsyWebsocket/${data.userId}/${data.sid}`);
            state.ws.onopen = () => {
                console.log('建立连接');
            };
            state.ws.onmessage = (evt) => {
                console.log(evt)
                window.store.commit('chat/GET_MESSAGES', evt)
            };
        },
        // 收到消息
        GET_MESSAGES({ sessions }, content) {
            const msg = JSON.parse(content.data)
            let session = sessions.find(item => item.user.userId == msg.userId);
            session.messages.push({
                userId: msg.userId,
                msg: msg.msg,
                date: new Date(),
            });
        },
        // 发送消息
        SEND_MESSAGE({ ws, sessions, currentSessionId }, content) {
            const data = {
                userId: currentSessionId,
                msg: content,
                date: new Date(),
                self: true
            }
            ws.send(JSON.stringify(data));
            let session = sessions.find(item => item.user.userId === currentSessionId);
            session.messages.push(data);
        },
        // 选择会话
        SELECT_SESSION(state, id) {
            state.currentSessionId = id;
        },
        // 搜索
        SET_FILTER_KEY(state, value) {
            state.filterKey = value;
        },

        ADD_MESSAGE({ sessions }, content) {
            let isSession = sessions.some(item => item.user.userId == content.userId);
            if (!isSession) {
                sessions.push({ user: content, messages: [] })
            }
            window.store.commit('chat/SELECT_SESSION', content.userId)
        }
    },
    actions: {
        // 添加当前登录人信息到chat
        setUser: (store, content) => store.commit('SET_USERS', content),
        // 初始化WebSocket
        initWs: (store) => {
            return utils.get(utils.api.websocketURL.view, (res) => store.commit('INIT_WS', res));
        },
        sendMessage: (store, content) => store.commit('SEND_MESSAGE', content),
        selectSession: (store, id) => store.commit('SELECT_SESSION', id),
        // 搜索聊天
        search: (store, value) => store.commit('SET_FILTER_KEY', value),
        // 建立；聊天
        addMssage: (store, content) => store.commit('ADD_MESSAGE', content),
        // 收到消息
        getMessage: (store, content) => store.commit('GET_MESSAGES', content),
    }
})

export default window.store